package com.java.distributed.filter;

import com.java.distributed.beans.MySession;
import com.java.distributed.service.MySessionService;
import org.apache.catalina.connector.RequestFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.UUID;

@WebFilter
@Order(-1000)
//@Component
public class MyWrapperFilter implements Filter {

    @Autowired
    private MySessionService mySessionService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        SessionHttpServletRequest sessionHttpServletRequest = new SessionHttpServletRequest((HttpServletRequest) servletRequest);
        sessionHttpServletRequest.setResponse((HttpServletResponse) servletResponse);
        filterChain.doFilter(sessionHttpServletRequest, servletResponse);

        //后面的过滤器走完之后 会走这边
        HttpSession session = sessionHttpServletRequest.getSession();
        mySessionService.setSession((MySession) session);
        return;
    }

    @Override
    public void destroy() {

    }

    class SessionHttpServletRequest extends HttpServletRequestWrapper {

        private HttpServletRequest request;

        private HttpServletResponse response;

        public SessionHttpServletRequest(HttpServletRequest request) {
            super(request);
            this.request = request;
        }

        public void setResponse(HttpServletResponse response) {
            this.response = response;
        }

        @Override
        public HttpSession getSession() {
            MySession session = mySessionService.getSession(request, response);
            return session;
        }
    }
}
